package com.zj.sixtyDayChallenge.tree;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @program: algorithm
 * @description: 左叶子之和
 * 404 sum-of-left-leaves
 * //给定二叉树的根节点 root ，返回所有左叶子之和。
 * //
 * //
 * //
 * // 示例 1：
 * //
 * //
 * //
 * //
 * //输入: root = [3,9,20,null,null,15,7]
 * //输出: 24
 * //解释: 在这个二叉树中，有两个左叶子，分别是 9 和 15，所以返回 24
 * //
 * //
 * // 示例 2:
 * //
 * //
 * //输入: root = [1]
 * //输出: 0
 * //
 * //
 * //
 * //
 * // 提示:
 * //
 * //
 * // 节点数在 [1, 1000] 范围内
 * // -1000 <= Node.val <= 1000
 * //
 * //
 * //
 * //
 * // Related Topics 树 深度优先搜索 广度优先搜索 二叉树 👍 554 👎 0
 * @author: Zhang Bo
 * @create: 2022-01-14 17:05
 **/
public class SumOfLeftLeaves {
    public static void main(String[] args) {
        Solution solution = new SumOfLeftLeaves().new Solution();
    }
    //leetcode submit region begin(Prohibit modification and deletion)

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    class Solution {
        public int sumOfLeftLeaves(TreeNode root) {
            int sum = 0;
            Queue<TreeNode> queue = new LinkedList<>();
            queue.offer(root);
            while (!queue.isEmpty()) {
                TreeNode poll = queue.poll();


                if (poll.left != null) {
                    if (this.leaf(poll.left)) {
                        sum += poll.left.val;
                    }
                    queue.offer(poll.left);
                }

                if (poll.right != null) {
                    queue.offer(poll.right);
                }
            }

            return sum;

        }

        private boolean leaf(TreeNode tree) {
            return tree.left == null && tree.right == null;
        }


    }
//leetcode submit region end(Prohibit modification and deletion)

}